package com.ruoyi.system.dao;

import com.ruoyi.common.core.dao.BaseDao;
import com.ruoyi.common.utils.ConvertUtil;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.groupkey.SysUserRoleKey;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户与角色关联表 数据层
 *
 * @author liuyj
 */
@Repository
public class SysUserRoleDao extends BaseDao<SysUserRole, SysUserRoleKey> {
    /**
     * 通过用户ID删除用户和角色关联
     *
     * @param userId 用户ID
     * @return 结果
     */
    public int deleteUserRoleByUserId(Long userId){
        String hql="delete from SysUserRole where userId="+userId;
        return this.executeHql(hql);
    }

    /**
     * 批量删除用户和角色关联
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    public int deleteUserRole(Long[] ids){
        String hql = "delete from SysUserRole  where userId in "+ ConvertUtil.toDbString(ids);
        return this.executeHql(hql);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    public int countUserRoleByRoleId(Long roleId){
        String hql = "select count(1) from SysUserRole  where roleId ="+ roleId;
        Long total = (Long) this.find(hql).get(0);
        return total.intValue();
    }

    /**
     * 删除用户和角色关联信息
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    public int deleteUserRoleInfo(SysUserRole userRole){
        String hql="delete from SysUserRole where userId="+userRole.getUserId()+" and roleId="+userRole.getRoleId();
        return this.executeHql(hql);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int deleteUserRoleInfos(Long roleId, Long[] userIds){
        String hql="delete from SysUserRole where roleId="+roleId+" and userId in "+ ConvertUtil.toDbString(userIds);
        return this.executeHql(hql);
    }

    /**
     * 通过用户ID获取用户角色列表
     * @param userId 用户ID
     * @return 用户角色列表
     */
    public List<SysUserRole> findByUserId(Long userId){
        String hql="from SysUserRole where userId="+userId;
        return this.find(hql);
    }

}
